﻿using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Terraria.Audio;
using Terraria.ModLoader;
using Terraria.UI;

namespace WorseGame.Common.UIs.Elements
{
    public class PlayerFishBar : UIElement
    {
        public static readonly SoundStyle GroundTapSound = new(nameof(WorseGame) + "/Assets/Sounds/GroundTap");

        public float verticalVelocity;
        public bool playerHoldingDownLMB;
        public bool barOverFish;

        private Texture2D _texture;

        public PlayerFishBar()
        {
            HAlign = 0.5f;
            VAlign = 1f;
            Height.Set(0f, 0.175f);
            Left.Set(5f, 0f);
            _texture = ModContent.Request<Texture2D>("WorseGame/Assets/Textures/UIs/MiniGameBar", ReLogic.Content.AssetRequestMode.ImmediateLoad).Value;
        }

        protected override void DrawSelf(SpriteBatch spriteBatch)
        {
            var dimensions = GetDimensions();

            Color drawColor = barOverFish ? Color.White : Color.White * 0.8f;
            var destRect = new Rectangle(
                (int)dimensions.X,
                (int)dimensions.Y,
                (int)dimensions.Width,
                (int)dimensions.Height
            );

            spriteBatch.Draw(_texture, destRect, drawColor);
        }

        public override void Update(GameTime gameTime)
        {
            base.Update(gameTime);

            VAlign = MathHelper.Clamp(VAlign + verticalVelocity, 0f, 1f);

            if (VAlign == 1f && verticalVelocity >= 0.0025)
            {
                verticalVelocity = -verticalVelocity * 0.55f;
                SoundEngine.PlaySound(GroundTapSound);
            }

            if ((VAlign == 1f && verticalVelocity > 0f) || (VAlign == 0f && verticalVelocity < 0f))
            {
                verticalVelocity = 0f;
            }
            else
            {
                verticalVelocity = MathHelper.Clamp(verticalVelocity, -0.05f, 0.05f);
            }

            if (playerHoldingDownLMB)
            {
                verticalVelocity -= 1f / 1600f;
            }
            else if (VAlign != 1f)
            {
                verticalVelocity += 1f / 2400f;
            }
        }
    }
}